package com.shengqi.xinnongren.work.ui.user.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.utils.BitmapHelper;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.RxGalleryMyApi;
import com.shengqi.xinnongren.common.utils.SimpleRxGalleryFinal;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.common.utils.ToastUtils;
import com.shengqi.xinnongren.work.ui.user.model.CommentGoodsModel;
import com.shengqi.xinnongren.work.ui.user.model.UploadPicBean;
import com.shengqi.xinnongren.work.ui.user.presenter.CommitCommentPresenter;
import com.shengqi.xinnongren.work.ui.user.view.CommitCommentView;
import com.yalantis.ucrop.util.FileUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultDisposable;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import cn.finalteam.rxgalleryfinal.ui.base.IRadioImageCheckedListener;

public class CommitCommentActivity extends BaseMvpActivity<CommitCommentView, CommitCommentPresenter> implements CommitCommentView {

    private static final String EXTRA_ORDER_ID = "order_id";
    @BindView(R.id.rv_comment)
    RecyclerView mRvComment;

    String mOrderId = "";

    int clickItem = -1;
    private ArrayList<CommentGoodsModel> mCommentGoodsModelList;
    private CommentAdapter mAdapter;

    public static void start(Context context, String orderId) {
        Intent intent = new Intent(context, CommitCommentActivity.class);
        intent.putExtra(EXTRA_ORDER_ID, orderId);
        context.startActivity(intent);
    }

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_commit_comment;
    }

    @Override
    protected void initView() {
        mOrderId = getIntent().getStringExtra(EXTRA_ORDER_ID);
        mCommentGoodsModelList = new ArrayList<>();
        mAdapter = new CommentAdapter(mCommentGoodsModelList);
        mRvComment.setAdapter(mAdapter);
        mRvComment.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
    }

    @OnClick(R.id.tv_commit)
    void tv_commit() {
        mPresenter.addComment(mOrderId, mCommentGoodsModelList);
    }

    @Override
    protected void initData() {
        mPresenter.getCommitOrderInfo(mOrderId);
    }

    @Override
    protected CommitCommentPresenter createPresenter() {
        return new CommitCommentPresenter();
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingView();
    }

    @Override
    public void onUploadPicSucceed(List<UploadPicBean> picBeanList) {
        if (picBeanList.size() == 0)
            return;
        if (clickItem < 0)
            return;
        mAdapter.addPic(clickItem, picBeanList.get(0));
        clickItem = -1;
    }

    @Override
    public void onGetCommitOrderInfoSucceed(List<CommentGoodsModel> list) {
        mCommentGoodsModelList.clear();
        mCommentGoodsModelList.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRequestFailed(String message) {
        hideLoadingView();
        ToastHelper.getInstance(this).showWarn(message);
    }

    @Override
    public void onAddCommentSucceed(String message) {
        ToastHelper.getInstance(this).showSucceed(message);
        finish();
    }

    class CommentAdapter extends RecyclerView.Adapter<CommentAdapter.Holder> {
        List<CommentGoodsModel> commentGoodsModelList;

        public CommentAdapter(List<CommentGoodsModel> commentGoodsModelList) {
            this.commentGoodsModelList = commentGoodsModelList;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_comment_goods, parent, false));
            holder.mRbGoods.setOnRatingBarChangeListener((ratingBar, rating, fromUser) -> {
                holder.mTvGoodsScore.setText(String.format("%s分", rating));
                mCommentGoodsModelList.get(holder.getAdapterPosition()).setGoodScore(rating);
            });
            holder.mEtGoodsComment.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    mCommentGoodsModelList.get(holder.getAdapterPosition()).setGoodsComment(s.toString());
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
            holder.mCbIsAnonymous.setOnCheckedChangeListener(
                    (buttonView, isChecked) -> mCommentGoodsModelList.get(holder.getAdapterPosition()).setAnonymous(isChecked)
            );
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position, @NonNull List<Object> payloads) {
            super.onBindViewHolder(holder, position, payloads);
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            holder.setPicList(commentGoodsModelList.get(holder.getAdapterPosition()).getPics());
            holder.mAdapter.setFatherPosition(position);
            holder.notifyDataSetChanged();
            CommentGoodsModel commentGoodsModel = commentGoodsModelList.get(position);
            holder.mRbGoods.setRating(commentGoodsModel.getGoodScore());
            ImageUtils.showImage(CommitCommentActivity.this, commentGoodsModel.getMainPic(), holder.mIvAvatar);
            holder.mTvNickname.setText(commentGoodsModel.getComName());
            holder.mTvTime.setText(commentGoodsModel.getDate());
            holder.mCbIsAnonymous.setChecked(commentGoodsModel.isAnonymous());
        }

        @Override
        public int getItemCount() {
            return commentGoodsModelList.size();
        }

        public void addPic(int position, UploadPicBean uploadPicBean) {
            commentGoodsModelList.get(position).addPic(uploadPicBean.viewPath);
            commentGoodsModelList.get(position).addSavePic(uploadPicBean.savePath);
            notifyDataSetChanged();
        }

        public class Holder extends RecyclerView.ViewHolder {
            private PicAdapter mAdapter;
            List<String> mPicList;

            @BindView(R.id.iv_avatar)
            ImageView mIvAvatar;
            @BindView(R.id.tv_nickname)
            TextView mTvNickname;
            @BindView(R.id.tv_time)
            TextView mTvTime;

            @BindView(R.id.rb_goods)
            RatingBar mRbGoods;
            @BindView(R.id.tv_goods_score)
            TextView mTvGoodsScore;
            @BindView(R.id.et_goods_comment)
            EditText mEtGoodsComment;

            @BindView(R.id.rv_pic)
            RecyclerView mRvPic;
            @BindView(R.id.cb_is_anonymous)
            CheckBox mCbIsAnonymous;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            public void notifyDataSetChanged() {
                mAdapter.notifyDataSetChanged();
            }

            public void setPicList(List<String> picList) {
                if (mPicList == picList)
                    return;
                mPicList = picList;
                initList();
            }

            private void initList() {
                mAdapter = new PicAdapter(CommitCommentActivity.this, mPicList, getAdapterPosition());
                mRvPic.setAdapter(mAdapter);
                mRvPic.setLayoutManager(new GridLayoutManager(CommitCommentActivity.this, 4) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
            }
        }

    }


    class PicAdapter extends RecyclerView.Adapter<PicAdapter.Holder> {

        private Context mContext;
        private List<String> mPicList;
        int mFatherPosition;

        public PicAdapter(Context context, List<String> picList, int fatherPosition) {
            mContext = context;
            mPicList = picList;
            mFatherPosition = fatherPosition;
        }

        public void setFatherPosition(int fatherPosition) {
            mFatherPosition = fatherPosition;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_choose_pic, parent, false));
            holder.ivPic.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewGroup.LayoutParams layoutParams = holder.ivPic.getLayoutParams();
                    layoutParams.height = holder.ivPic.getWidth();
                    holder.ivPic.setLayoutParams(layoutParams);
                    holder.ivPic.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
            holder.itemView.setOnClickListener(v -> {
                if (holder.getAdapterPosition() == mPicList.size()) {
//                        ToastHelper.getInstance(mContext).showNormal("" + mFatherPosition);
                    AndPermission.with(mContext).permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE).onGranted(permissions -> {
                        if (mCommentGoodsModelList.get(mFatherPosition).getPics().size() >= 4) {
                            ToastHelper.getInstance(mContext).showWarn("最多只能上传四张图片");
                            return;
                        }
                        clickItem = mFatherPosition;
                        chooseFromAlbum();
                    }).start();
                }
            });
            holder.vReduce.setOnClickListener(v -> {
                mPicList.remove(holder.getAdapterPosition());
                notifyDataSetChanged();
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            if (position != mPicList.size()) {
                Glide.with(CommitCommentActivity.this).load(mPicList.get(position)).into(holder.ivPic);
                holder.vReduce.setVisibility(View.VISIBLE);
            } else {
                holder.ivPic.setImageResource(R.drawable.ic_add_pic);
                holder.vReduce.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return mPicList.size() + 1;
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_pic)
            ImageView ivPic;
            @BindView(R.id.v_reduce)
            View vReduce;

            public Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    private void chooseFromAlbum() {
        RxGalleryMyApi instance =
                RxGalleryMyApi.getInstance(this);
        instance.openGalleryRadioImgDefault(new RxBusResultDisposable<ImageRadioResultEvent>() {
            @Override
            protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
                LogUtil.i("只要选择图片就会触发");
            }
        }).onCropImageResult(
                new IRadioImageCheckedListener() {
                    @Override
                    public void cropAfter(Object t) {
                        File file = (File) t;
//                        RequestOptions options = new RequestOptions();
//                        options.centerCrop();
//                        compressAndUploadHeadImg(file.getAbsolutePath());
                        doSomethingWithFile(file);
                        LogUtil.i("裁剪完成");
                    }

                    @Override
                    public boolean isActivityFinish() {
                        LogUtil.i("返回false不关闭，返回true则为关闭");
                        return true;
                    }
                });
    }

    private void takePhoto() {
        SimpleRxGalleryFinal.get().init(
                new SimpleRxGalleryFinal.RxGalleryFinalCropListener() {
                    @NonNull
                    @Override
                    public Activity getSimpleActivity() {
                        return CommitCommentActivity.this;
                    }

                    @Override
                    public void onCropCancel() {
                        ToastUtils.showShort(getSimpleActivity(), "操作被取消");
                    }

                    @Override
                    public void onCropSuccess(@Nullable Uri uri) {
                        if (uri != null) {
                            String path = FileUtils.getPath(getSimpleActivity(), uri);
                            compressAndUploadHeadImg(path);
                        } else {
                            ToastUtils.showShort(getSimpleActivity(), "图片不存在");
                        }
                    }

                    @Override
                    public void onCropError(@NonNull String errorMessage) {
                        ToastUtils.showShort(getSimpleActivity(), errorMessage);
                    }
                }
        ).openCamera();
    }

    private void compressAndUploadHeadImg(String path) {
        File file = new File(path);
        // 压缩头像并保存
        Bitmap bitmap = BitmapHelper
                .compressImage(BitmapFactory.decodeFile(file.getAbsolutePath()));
        LogUtil.e(file.getParent());
        File PHOTO_DIR = new File(file.getParent());
        File headFile = new File(PHOTO_DIR, "head.jpg");//设置文件名称
        if (headFile.exists()) {
            headFile.delete();
        }
        try {
            headFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(headFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 上传用户头像
        LogUtil.e(headFile.getAbsolutePath());
        doSomethingWithFile(headFile);
    }

    private void doSomethingWithFile(File headFile) {
        mPresenter.updateHeadImg(headFile);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SimpleRxGalleryFinal.get().onActivityResult(requestCode, resultCode, data);
    }
}
